/**
 * 提供两个接口，show和setReason
 */
function FaultDiscMan(){
	var currentReason = "覆冰";
	var startYear;
	var endYear;
	var currentMonth = 0;
	var rightDivId = 'affectObjDiv';
	var radius = 50;//热点图的半径
	var panel;
	function show(){
		clearAll();
		panel = new PanelTablesUtil(rightDivId);
		panel.setTitle(currentReason+'故障');
		showInfo();
	}
	function hide(){
		TimelineSelector.hide();
	}
	function showInfo(){
		//改变查询模式
		var layerBtn = SelectLayerComponent.getBtn(false,changeLayer);
		panel.setTitleTool(layerBtn[0]);
		panel.setInfo(layerBtn[1]);
		if(currentReason=="雷击"){
			panel.setTitleTool('<i class="fa fa-bar-chart" title="故障分析"></i>',function(){
				MyModal.showModal("/ui/dataview/weatherdatamining/thunderDataMining.xhtml");
			});
		}
		if(currentReason=="山火"){
			panel.setTitleTool('<i class="fa fa-bar-chart" title="故障分析"></i>',function(){
				MyModal.showModal("/ui/dataview/devicefault/transmissionLineDialog.xhtml?selectedFaultReason="+currentReason);
			});
		}
		
		YearModelDrawer.show();
		panel.show();
	}
	function changeLayer(){
		DrawPointComponent.redraw();
	}
	/**
	 * 年份模式
	 * 提供一个接口：
	 * show()
	 */
	var YearModelDrawer = (function(){
		var resultDiv,title;
		function show(){
			var queryDiv = QueryDivComponent.getQueryDiv(changeYear);
			panel.setInfo(queryDiv);
			title = $('<span>'+startYear+"~"+endYear+currentReason+"故障</span>");
			resultDiv = panel.getCollapsePanelEle("faultDiscYearResult",title,true);
			changeYear();
		}
		function changeYear(){
			QueryDivComponent.updateStartAndEnd();
			TimelineSelector.draw(changeYear,query);
			query(0);
		}
		//画出来结果，每次changemonth，也是query，changeyear也是。但是 changeyear需要重新画时间轴。
		function query(){
			resultDiv.html('');
			title.html(getTitle());
			resultDiv.html(PanelTablesUtil.getNoDataDiv("加载中..."));
			DrawPointComponent.clear();
			//使用encodeURIComponent，解决IE9中文编码格式不同的问题
			var url = '/rest/fault/getFaultByReasonAndDate/'+startYear+'/'+endYear
			+'/'+encodeURIComponent(currentReason)+'/'+currentMonth;
			$.ajax({
				   type: "GET",
				   url: url,
				   success: function(result){
					   result = eval('('+result+')');
					   resultDiv.html('');
					   if(result && result.tableData && result.tableData.length>0){
						   drawTable(result.tableData);
						   DrawPointComponent.draw(result.heatMapData,result.scatterMapData);
					   }else{
						   resultDiv.html(PanelTablesUtil.getSmileInfo('无故障发生'));
					   }
				   },
				   error:function(err){
					   resultDiv.html(PanelTablesUtil.getNoDataDiv('查询出错！'));
				   }
				});
		}
		function drawTable(data){
			RightTableDrawer.draw(title,resultDiv,data);
		}
		function getTitle(){
			return startYear +(startYear == endYear?'':'~'+endYear)+'年'
			+(currentMonth == 0?'':currentMonth+'月')+currentReason+'故障';
		}
		return {
			show:show
		};
	})();
	/**
	 * 画右侧表格，提供接口：draw()需要传参：表格的标题的jquery引用，表格的父的jquery引用,数据
	 */
	var RightTableDrawer = (function(){
		function getTitle(){
			return startYear +(startYear == endYear?'':'~'+endYear)+'年'
			+(currentMonth == 0?'':currentMonth+'月')+currentReason+'故障';
		}
		function draw(title,resultDiv,data){
			title.html(getTitle()+'<span title="故障次数" class="badge bg-red pull-right">'+getFaultNum(data)+'</span>');
			var table = $('<table class="table table-bordered table-hover"></table>').appendTo(resultDiv);
			var opt = MyTable.getDefaultOptions();
			opt.scrollX = false;
			opt.autoWidth = false;
			opt.scrollY = 300;
			opt.scrollCollapse = true;
			var t = new MyTable(table, ['故障设备','故障次数'], opt);
			t.setDataSet(getArrayDataset(data));
			t.show();
			t.onRowClick(function(data) {
				if (data) {
					searchSelectObj(data[0],true,false,data[2]);
				}
			});
		}
		function getFaultNum(data){
			var sum = 0;
			for(var i in data){
				sum += data[i][1];
			}
			return sum;
		}
		function getArrayDataset(data){
			var ds = [];
			for(var i in data){
				ds.push([data[i][0],data[i][1],data[i][3]]);
			}
			return ds;
		}
		function getDataset(data){
			var ds = [];
			for(var i in data){
				var t = new Date(data[i].faultTime.time);
				var d = [t.toLocaleDateString(),data[i].equipment?data[i].equipment:'',data[i].startPole?data[i].startPole:''];
				ds.push(d);
			}
			return ds;
			function sortData(obj1,obj2){
				return obj1.faultTime.time - obj2.faultTime.time;
			}
			function getDayTimeStr(millis){
				var t = new Date(millis);
				var m = t.getMonth() + 1 > 9 ? (t.getMonth() + 1) : ("0" + (t.getMonth() + 1));
				var d = t.getDate() > 9 ? t.getDate() : "0" + t.getDate();
				var timestr = t.getFullYear() + "-" + m + "-" + d;
				return timestr;
			}
		}
		return {
			draw:draw
		};
	})();
	/**
	 * 时间轴选择器，提供接口：draw(year,ms,onchangeYear,onchangeMonth),hide()
	 */
	var TimelineSelector = (function(){
		var bottomTitle = $('#bottom_title');
		var bottomDiv = $('#bottomDiv');
		var timeline = $('#bottomTimeline');
		var allMonths = [0,1,2,3,4,5,6,7,8,9,10,11,12];
		var months = [];
		
		function show(onChangeYear,onChangeMonth){
			drawBottomTitle(onChangeYear);
			drawBottomDiv(onChangeMonth);
		}
		function drawBottomDiv(callback){
			bottomDiv.css("display",'block');
			if(months && months.length == 0){
				timeline.html(PanelTablesUtil.getSmileInfo("一次设备（500kv）未发生"+currentReason+"故障。"));
			}else{
				timeLineObj = new TimeLine("bottomTimeline");
				timeLineObj.setTimeDatas(getMonths());
				var opt = timeLineObj.getOption().baseOption;
				opt.backgroundColor = 'transparent';
				opt.timeline.controlStyle.show = true;
				opt.timeline.controlStyle.showPlayBtn = false;
				opt.timeline.controlStyle.showNextBtn = true;
				opt.timeline.controlStyle.showPrevBtn = true;
				opt.timeline.top = '40%';
				opt.timeline.currentIndex = currentMonth;
				timeLineObj.show();
				timeLineObj.getChart().on('timelinechanged', function (params) {
					currentMonth = allMonths[params.currentIndex];
					callback();
				});
			}
		}
		function getMonths(){
			var ms = [];
			for(var i in allMonths){
				if(i == 0){
					ms[i] = {value:"全部",symbol:"diamond",symbolSize:18};
				}else{
					ms[i] = allMonths[i]+"月";
					for(var j in months){
						if(allMonths[i] == months[j]){
							ms[i] = {value:months[j]+"月",symbol:'diamond',symbolSize:16};
							break;
						}
					}
				}
			}
			return ms;
		}
		//title，需要两个方法，一个lastYear,ne
		function drawBottomTitle(callback){
			bottomTitle.css('display','block');
			bottomTitle.html('');
			var ul = $('<div class="btn-group"></div>').appendTo(bottomTitle);
			var lastBtn = $('<button class="btn btn-primary">'+startYear+'</button>').appendTo(ul);
			var yearBtn = $('<button class="btn btn-primary">~</button>').appendTo(ul);
			var nextBtn = $('<button class="btn btn-primary" >'+endYear+'</button>').appendTo(ul);
			var d = new Date();
			d.setFullYear(startYear);
			lastBtn.datetimepicker({
				format : 'yyyy',
				minView : 4,
				pickerPosition:'top-right',
				autoclose : true,
				todayHighlight : true,
				startView:4,
				endDate:new Date(),
				initialDate:d
			}).on('changeYear', function(ev){
				startYear = ev.date.getFullYear();
				callback();
			});
			var e = new Date();
			e.setFullYear(endYear);
			nextBtn.datetimepicker({
				format : 'yyyy',
				minView : 4,
				pickerPosition:'top-right',
				autoclose : true,
				todayHighlight : true,
				startView:4,
				endDate:new Date(),
				initialDate:e
			}).on('changeYear', function(ev){
				endYear = ev.date.getFullYear();
				callback();
			});
		}
		return {
			draw:function(onChangeYear,onChangeMonth){
				$.getJSON("/rest/fault/getFaultMonthByReasonAndYear/"+currentReason+"/"+startYear+"/"+endYear,function(result){
					months = result;
					show(onChangeYear,onChangeMonth);
				});
			},
			hide:function(){
				bottomTitle.css('display','none');
				bottomDiv.css('display','none');
			}
		};
	})();
	/**
	 * 选择热点图，散点图，网格图的组件
	 * 开放接口：
	 * getBtn(isShow,callback)
	 * 返回一个数组，第一个是jquery的按钮，第二个是jquery的收缩选择框
	 * 参数：isShow：收缩框默认是否显示。callback：选择发生时，调用此方法。  
	 */
	var SelectLayerComponent = (function(){
		var layerTypes = ['散点图','热点图','网格图'];
		var currentType = '热点图';
		var div,btn;
		function drawDiv(isShow,callback){
			div = $('<div class="panel-collapse collapse" />');
			var table = $('<table/>').appendTo(div);
			var tr = $('<tr/>').appendTo(table);
			for(var i in layerTypes){
				getTd(layerTypes[i]).appendTo(tr);
			}
			if(isShow){
				div.addClass('in');
			}
			function getTd(value){
				var td = $('<td/>');
				var label = $('<label />').appendTo(td);
				var input = $('<input style="margin:5px;" type="radio" value="'+value+'" name="faultLayerType">').appendTo(label);
				label.append(value);
				if(currentType == value){
					input.attr('checked','checked');
				}
				input.change(function(){
					if(this.checked){
						currentType = this.value;
						callback(this.value);
					}
				});
				return td;
			}
		}
		return {
			getBtn:function(isShow,callback){
				drawDiv(isShow,callback);
				btn = $('<i class="fa fa-cogs"></i>');
				btn.click(function(){
					div.collapse('toggle');
				});
				return [btn,div];
			},
			getCurrentType:function(){
				return currentType;
			}
		};
	})();
	/**
	 * 查询组件
	 * 提供两个接口：getQueryDiv(callback)
	 * callback:查询方法
	 */
	var QueryDivComponent = (function() {
		var div,restore,query,minus,start,end;
		startYear = endYear = new Date().getFullYear();
		
		function getQueryDiv(callback){
			div = $('<div style="display:flex;"/>');
			minus = $('<span class="btn btn-default" ><i class="fa fa-arrow-left"></i></span>').appendTo(div);
			start = $('<input type="text" class="form-control ice-warning-start"/>').appendTo(div);
			end = $('<input type="text" class="form-control ice-warning-end"/>').appendTo(div);
			restore = $('<span class="btn btn-default" ><i class="fa fa-repeat"></i></span>').appendTo(div);
			query = $('<span class="btn btn-default" >搜索</span>' ).appendTo(div);
			
			query.click(function(){
				startYear = start.val();
				endYear = end.val();
				if(endYear>new Date().getFullYear()){
					endYear = new Date().getFullYear();
				}
				callback();
			});
			restore.click(function(){
				startYear = endYear = new Date().getFullYear();
				start.val(startYear);
				end.val(endYear);
			});
			minus.click(function(){
				startYear = Number(startYear)-1;
				start.val(startYear);
				endYear = Number(endYear)-1;
				end.val(endYear);
			});
			start.datetimepicker({
				format : 'yyyy',
				minView : 4,
				pickerPosition:'bottom-right',
				autoclose : true,
				startView:4,
				endDate:new Date(),
				initialDate:new Date()
			}).on('changeYear', function(ev){
				startYear = ev.date.getFullYear();
			});
			end.datetimepicker({
				format : 'yyyy',
				minView : 4,
				pickerPosition:'bottom-left',
				autoclose : true,
				startView:4,
				endDate:new Date(),
				initialDate:new Date()
			}).on('changeYear', function(ev){
				endYear = ev.date.getFullYear();
			});
			start.val(startYear);
			end.val(endYear);
			return div;
		}
		return {
			getQueryDiv:getQueryDiv,
			updateStartAndEnd:function(){
				start.val(startYear);
				end.val(endYear);
			}
		};
	})();
	/**
	 * 根据layer画图，提供两个接口：draw(data),redraw(),clear()
	 */
	var DrawPointComponent = (function(){
		var layerTypes = {
				'散点图':weatherLayer,
				'热点图':heatMapLayer,
				'网格图':heatGridLayer
				};
		var currentLayerType;
		var data;
		function clear(){
			for(var i in layerTypes){
				layerTypes[i].removeAllFeatures();
			}
		}
		function drawPoints(heatMapData,scatterMapData){
			if(drawPoints && scatterMapData){
				data = {heatMapData:heatMapData,scatterMapData:scatterMapData};
			}
			clear();
			currentLayerType = SelectLayerComponent.getCurrentType();
			var layer = layerTypes[currentLayerType];
			switch (currentLayerType){
			case '散点图':drawScatter(data.scatterMapData,layer);break;
			case '热点图':drawHeatPoint(data.heatMapData,layer);break;
			case '网格图':drawHeatGrid(data.heatMapData,layer);break;
			}
		}
		function drawScatter(data,layer){
			var heatPoints = [];
			for(var i in data){
				var value = data[i];
				var p = new SuperMap.Feature.Vector(
						new SuperMap.Geometry.Point(value.lon,value.lat));
				p.style = getPointStyle(value.radius);
				heatPoints.push(p);
			}
			layer.addFeatures(heatPoints);
			layer.setVisibility(true);
			
		}
		function drawHeatPoint(data,layer){
			var heatPoints = [];
			if(currentLayerType == '热点图'){
				layer.radius = radius;//热点图需要
			}
			for(var i in data){
				var value = data[i];
				var p = new SuperMap.Feature.Vector(
						new SuperMap.Geometry.Point(value.lon,value.lat), {
							"value" : 1,//热点图需要
						});
				heatPoints.push(p);
			}
			layer.addFeatures(heatPoints);
			layer.setVisibility(true);
			
		}
		function drawHeatGrid(data,layer){
			var heatPoints = [];
			if(currentLayerType == '网格图'){
				layer.items = getGridLayerItems(data.length);//网格图需要
			}
			for(var i in data){
				var value = data[i];
				var p = new SuperMap.Feature.Vector(
						new SuperMap.Geometry.Point(value.lon,value.lat));
				p.style = getPointStyle();
				heatPoints.push(p);
			}
			layer.addFeatures(heatPoints);
			layer.setVisibility(true);
			
		}
		function getPointStyle(value){
			value = value?value:0;
			return {
					fillColor : "red",
					strokeColor : "yellow",
					pointRadius : 5+value*3
			};
		}
		function getGridLayerItems(max){
			var colors = ['#FFDD55','#FFAA33','#EE7700','orangeRed','red','#AA0000'];
			var strokeColor = 'orange';
			var items = [];
			var last = 1;
			var length = colors.length > Math.ceil(max/2)?Math.ceil(max/2):colors.length;
			var countStep = max/length/3*2;//取最大值的三分之二分级
			for(var i=0;i<length;i++){
				var end = Math.ceil((i+1)*countStep);
				items.push({
					start:last,
					end:end,
					style:{
						strokeColor:strokeColor,
						strokeWidth:1,
						fillColor:colors[i],
						fillOpacity:0.7
					}
				});
				last = end;
			}
			items[items.length-1].end = max+1;
			return items;
		}
		
		return {
			draw:drawPoints,
			redraw:function(){
				drawPoints();
			},
			clear:clear
		};
	})();
	return {
		show:show,
		setReason:function(reason){
			currentReason = reason;
			return this;
		},
		hide:hide
	};
}


function FaultDiscMan1(){
	var currentReason = "覆冰";
	var currentMonth = 1;
	var currentYear = endYear;
	
	var rightDivId = 'affectObjDiv';
	var bottomTitleId = "bottom_title";
	var bottomDivId = 'bottomDiv';
	var timelineId = 'bottomTimeline';
	var currentYearId = 'faultCurrentYear';
	var changeLayerTypeDivId = 'changeLayerTypeDiv';
	var tableId = 'faultDiscTable';
	
	var panelCollapse = true;
	
	//散点图，热点图，热点网格图
	var layerSelectOpen = false;
	var currentLayerType = 'heatMap';
	var layerTypes = {
			'scatter':weatherLayer,
			'heatMap':heatMapLayer,
			'heatGrid':heatGridLayer
			};
	
	var endYear = new Date().getFullYear();
	var allMonths = [1,2,3,4,5,6,7,8,9,10,11,12];
	var months = [];
	var monthData = {};
	var radius = 50;
	var pointStyle = {
			fillColor : "red",
			strokeColor : "yellow",
			pointRadius : 5
	};
	this.setReason = function(reason){
		currentReason = reason;
		monthData = {};
		currentMonth = 1;
		currentYear = new Date().getFullYear();
		return this;
	};
	this.show = function(){
		clearAll();
		loadData();
	};
	this.changeYear = function(year){
		if(currentYear != year){
			currentYear = year;
			currentMonth = 1;
			loadData();
		}
	};
	this.nextYear = function(){
		currentYear ++;
		loadData();
	};
	this.lastYear = function(){
		currentYear --;
		loadData();
	};
	this.hide = function(){
		heatMapLayer.removeAllFeatures();
		$('#'+rightDivId).css('display','none');
		$('#'+bottomTitleId).css('display','none');
		$('#'+bottomDivId).css('display','none');
	};
	this.onChangeLayerTypeBtnClick = function(){
		var div = $('#'+changeLayerTypeDivId);
		if (div.hasClass('in')) {
			div.collapse('hide');
			layerSelectOpen = false;
		} else {
			div.collapse('show');
			layerSelectOpen = true;
		}
	};
	this.changeLayerType = function(type){
		if(type == currentLayerType){
			return;
		}else{
			layerTypes[currentLayerType].removeAllFeatures();
			currentLayerType = type;
			drawMapPoint();
		}
	};
	this.changePanelCollapse = function(){
		panelCollapse = !panelCollapse;
	};
	function loadData(){
		monthData = {};
		$.getJSON("/rest/fault/getFaultMonthByReasonAndYear/"+currentReason+"/"+currentYear,function(result){
			months = result;
			show();
		});
	}
	function show(){
		clearAll();
		if( !months || months.length == 0){
			showNoMonth();
		}else{
			currentMonth = months[0]; 
			showCurrentMonth();
		}
		drawBottomDiv();
	}
	function showCurrentMonth(){
		if(monthData[currentMonth]){
			drawMapPoint();
			drawRightDiv();
		}else{
			loadMonthData();
		}
	}
	function loadMonthData(){
		$.getJSON("/rest/fault/getFaultsByReasonAndYearAndMonth/"+currentReason
				+"/"+currentYear+"/"+currentMonth,function(result){
			monthData[currentMonth] = result;
			drawMapPoint();
			drawRightDiv();
		});
	}
	function drawMapPoint(){
		var layer = layerTypes[currentLayerType];
		layer.removeAllFeatures();
		var data = monthData[currentMonth];
		switch (currentLayerType) {
		case 'heatMap':drawHeatMapPoints(data,layer);break;
		case 'heatGrid':drawHeatGridPoints(data,layer);break;
		case 'scatter':drawScatterPoints(data,layer);break;
		}
	}
	function drawScatterPoints(faults,layer) {
		var points = [];
		var map = getLonLatMap(faults);
		map.each(function(index, key, value){
			var p = new SuperMap.Feature.Vector(
					new SuperMap.Geometry.Point(value.geo[0],value.geo[1]), {
						"value" : value.value,
					});
			p.style = pointStyle;
			points.push(p);
		});
		layer.addFeatures(points);
		layer.setVisibility(true);
	}
	function drawHeatGridPoints(faults,layer) {
		var points = [];
		var map = getLonLatMap(faults);
		layer.items = getGridLayerItems(faults.length);
		map.each(function(index, key, value){
			var p = new SuperMap.Feature.Vector(
					new SuperMap.Geometry.Point(value.geo[0],value.geo[1]), {
						"value" : value.value,
					});
			p.style = pointStyle;
			points.push(p);
		});
		layer.addFeatures(points);
		layer.setVisibility(true);
	}
	function drawHeatMapPoints(faults,layer) {
		var heatPoints = [];
		var map = getLonLatMap(faults);
		layer.radius = radius;
		map.each(function(index, key, value){
			heatPoints[index] = new SuperMap.Feature.Vector(
					new SuperMap.Geometry.Point(value.geo[0],value.geo[1]), {
						"value" : value.value,
					});
		});
		layer.addFeatures(heatPoints);
		layer.setVisibility(true);
	}
	function getLonLatMap(faults){
		var map = new Map();
		for(var i =0;i<faults.length;i++){
			var x = faults[i].lon;
			var y = faults[i].lat;
			if(x && y){
				var val = map.get(x+","+y);
				if(val){
					//val.value ++;
				}else{
					val = {
							value:1,
							geo:[x,y]
					};
				}
				map.put(x+","+y,val);
			}
		}
		return map;
	}
	function showNoMonth(){
		var panel = new PanelTablesUtil(rightDivId);
		panel.setTitle(currentReason+"故障").setTitleTool('<i class="fa fa-cogs"></i>', "faultDiscMan.onChangeLayerTypeBtnClick();", 'changeLayerTypeBtn')
		if(currentReason=="雷击"){
			panel.setTitleTool('<i class="fa fa-bar-chart" title="故障分析"></i>',"faultDiscMan.openLJDlg()","ldfx");
		}
		panel.setInfo(getChangeLayerTypeDiv()+addNoInfo("本年度一次设备未发生"+currentReason+"故障。"));
		panel.show();
	}
	//点击故障分析打开雷电分析页面
	this.openLJDlg=function(){
		MyModal.showModal("/ui/dataview/weatherdatamining/thunderDataMining.xhtml");
	}
	function getChangeLayerTypeDiv(){
		var table = '<table><tr>';
		table += getTd('散点图','scatter',currentLayerType == 'scatter');
		table += getTd('热点图','heatMap',currentLayerType == 'heatMap');
		table += getTd('网格图','heatGrid',currentLayerType == 'heatGrid');
		table += '</tr></table>';
		var showDiv = layerSelectOpen?'in':'';
		var div = '<div class="panel-collapse collapse '+showDiv+'" id="'+changeLayerTypeDivId+'">';
		div += table;
		div += '</div>';
		function getTd(text,value,isSelected){
			var checked = isSelected?' checked="checked" ':'';
			return '<td><label><input style="margin:5px;" onchange="if(this.checked){faultDiscMan.changeLayerType(\''+value+'\');}" '+checked+' type="radio" name="layerType" />'+text+'</label></td>';
		}
		return div;
	}
	function drawRightDiv(){
		var panel = new PanelTablesUtil(rightDivId);
		panel.setTitle(currentReason+"故障").setTitleTool('<i class="fa fa-cogs"></i>', "faultDiscMan.onChangeLayerTypeBtnClick();", 'changeLayerTypeBtn');
		if(currentReason=="雷击"){
			panel.setTitleTool('<i class="fa fa-bar-chart" title="故障分析"></i>',"faultDiscMan.openLJDlg()","ldfx");
		}
		panel.setInfo(getChangeLayerTypeDiv());
		var tableTitle = currentYear+"年"+currentMonth+"月故障列表";
		var dataset = getDataset();
		if(dataset.length>0){
			tableTitle += '<span class="badge bg-red pull-right" title="本月发生'+currentReason+'故障的一次设备数">'+dataset.length+'</span>';
			var tb = panel.drawCollapseTable(tableId, tableTitle, panelCollapse,'faultDiscMan.changePanelCollapse();');
			var myOpt=MyCollapseTable.getDefaultOptions();
			myOpt.scrollY = 300;
			myOpt.scrollCollapse = true;
			myOpt.autoWidth = false;
			myOpt.columnDefs = [{ "width": "35%", "targets": 0 },
			                    { "width": "30%", "targets": 1 },
			                    { "width": "35%", "targets": 2 }];
			var tab = new MyTable(tb, ["故障时间","设备名","杆塔号"], myOpt);
			tab.setDataSet(dataset);
			tab.show();
			tab.onRowClick(function(data){
				if(data){
			    	$("#input_search").val(data[1]);
			    	searchObj();
				}
			});
			panel.setDangerBox();
		}else{
			var ele = panel.getCollapsePanelEle(tableId+"Parent",tableTitle,true);
			ele.append(addNoInfo("本月一次设备未发生"+currentReason+"故障。"));
			panel.setSuccessBox();
		}
		panel.show();
	}
	function getDataset(){
		var ds = [];
		var data = monthData[currentMonth];
		data.sort(sortData);
		for(var i in data){
			var t = new Date(data[i].faultTime.time);
			var d = [t.toLocaleDateString(),data[i].equipment?data[i].equipment:'',data[i].startPole?data[i].startPole:''];
			ds.push(d);
		}
		function sortData(obj1,obj2){
			return obj1.faultTime.time - obj2.faultTime.time;
		}
		return ds;
	}
	function addNoInfo(text){
		var info ='<div class="panel panel-default" style="margin:0;height:100px;background:none;">'
				+'<div class="col-md-12" style="text-align:center;padding-top:20px;">'
				+'<i class="fa fa-smile-o"  style="font-size:40px !important;color:green"></i>'
				+'<p class="text-success">'+text+'</p>'
				+'</div>'
				+'</div>';
		return info;
	};
	function drawBottomDiv(){
		drawBottomTitle();
		$('#'+bottomDivId).css("display",'block');
		if(months && months.length == 0){
			$('#'+timelineId).html(addNoInfo("本年度一次设备（500kv）未发生"+currentReason+"故障。"));
		}else{
			timeLineObj = new TimeLine(timelineId);
			timeLineObj.setTimeDatas(getMonths());
			var opt = timeLineObj.getOption().baseOption;
			opt.backgroundColor = 'transparent';
			opt.timeline.controlStyle.show = true;
			opt.timeline.controlStyle.showPlayBtn = false;
			opt.timeline.controlStyle.showNextBtn = true;
			opt.timeline.controlStyle.showPrevBtn = true;
			opt.timeline.top = '40%';
			opt.timeline.currentIndex = currentMonth-1;
			timeLineObj.show();
			timeLineObj.getChart().on('timelinechanged', function (params) {
				currentMonth = allMonths[params.currentIndex];
				showCurrentMonth();
			});
		}
	}
	function getMonths(){
		var ms = [];
		for(var i in allMonths){
			ms[i] = allMonths[i]+"月";
			for(var j in months){
				if(allMonths[i] == months[j]){
					ms[i] = {value:months[j]+"月",symbol:'diamond',symbolSize:16};
					break;
				}
			}
		}
		return ms;
	}
	function drawBottomTitle(){
		var title = $('#'+bottomTitleId);
		title.css('display','block');
		title.html('');
		var ul = $('<div class="btn-group"></div>');
		ul.append('<button class="btn btn-primary" onclick="faultDiscMan.lastYear()"><i class="fa fa-chevron-left" /></button>');
		ul.append('<button class="btn btn-primary" id="'+currentYearId+'">'+currentYear+'</button>');
		if(currentYear < endYear){
			ul.append('<button class="btn btn-primary" onclick="faultDiscMan.nextYear()"><i class="fa fa-chevron-right" /></button>');
		}else{
			ul.append('<button class="btn btn-primary disabled"><i class="fa fa-chevron-right"/></button>');
		}
		title.append(ul);
		setTimePicker(currentYearId,'top-right');
	}
	function setTimePicker(divId,pickerPosition){
		var d = new Date();
		d.setFullYear(currentYear, 0, 1);
		$('#'+divId).datetimepicker({
			format : 'yyyy',
			minView : 4,
			pickerPosition:pickerPosition,
			autoclose : true,
			todayHighlight : true,
			startView:4,
			endDate:new Date(),
			initialDate:d
		}).on('changeYear', function(ev){
			faultDiscMan.changeYear( ev.date.getFullYear());
		});
	}
	function changeMonth(month){
		currentMonth = month;
		showCurrentMonth();
	}
	function getGridLayerItems(max){
		var colors = ['#FFDD55','#FFAA33','#EE7700','orangeRed','red','#AA0000'];
		var strokeColor = 'orange';
		var items = [];
		var last = 1;
		var length = colors.length > Math.ceil(max/2)?Math.ceil(max/2):colors.length;
		var countStep = max/length/3*2;//取最大值的三分之二分级
		for(var i=0;i<length;i++){
			var end = Math.ceil((i+1)*countStep);
			items.push({
				start:last,
				end:end,
				style:{
					strokeColor:strokeColor,
					strokeWidth:1,
					fillColor:colors[i],
					fillOpacity:0.7
				}
			});
			last = end;
		}
		items[items.length-1].end = max+1;
		return items;
	}
	
}